document.addEventListener('DOMContentLoaded', () => {
    const registerForm = document.getElementById('registerForm');
    const phoneInput = document.getElementById('phone');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const phoneError = document.getElementById('phoneError');
    const passwordError = document.getElementById('passwordError');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const togglePassword = document.querySelector('.toggle-password');
    const toggleConfirmPassword = document.querySelector('.toggle-confirm-password');
    const submitBtn = document.querySelector('.register-submit');

    // 切换密码可见性
    togglePassword.addEventListener('click', () => {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        togglePassword.classList.toggle('fa-eye');
        togglePassword.classList.toggle('fa-eye-slash');
    });

    toggleConfirmPassword.addEventListener('click', () => {
        const type = confirmPasswordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        confirmPasswordInput.setAttribute('type', type);
        toggleConfirmPassword.classList.toggle('fa-eye');
        toggleConfirmPassword.classList.toggle('fa-eye-slash');
    });

    // 验证手机号
    const validatePhone = (phone) => {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    };

    // 验证密码强度
    const validatePassword = (password) => {
        return password.length >= 6 && /[A-Za-z]/.test(password) && /[0-9]/.test(password);
    };

    // 显示错误信息
    const showError = (element, message) => {
        element.textContent = message;
        element.style.display = 'block';
        element.style.animation = 'shake 0.5s';
    };

    // 清除错误信息
    const clearError = (element) => {
        element.textContent = '';
        element.style.display = 'none';
        element.style.animation = '';
    };

    // 实时验证手机号
    phoneInput.addEventListener('input', () => {
        if (!validatePhone(phoneInput.value)) {
            showError(phoneError, '请输入正确的手机号');
        } else {
            clearError(phoneError);
        }
    });

    // 实时验证密码
    passwordInput.addEventListener('input', () => {
        if (!validatePassword(passwordInput.value)) {
            showError(passwordError, '密码至少6位，包含字母和数字');
        } else {
            clearError(passwordError);
        }
        // 清除确认密码的错误提示
        clearError(confirmPasswordError);
    });

    // 确认密码输入时清除错误提示
    confirmPasswordInput.addEventListener('input', () => {
        clearError(confirmPasswordError);
    });

    // 输入框获得焦点时的效果
    [phoneInput, passwordInput, confirmPasswordInput].forEach(input => {
        input.addEventListener('focus', () => {
            input.parentElement.classList.add('focused');
        });

        input.addEventListener('blur', () => {
            input.parentElement.classList.remove('focused');
            if (!input.value) {
                input.parentElement.classList.remove('has-value');
            }
        });

        input.addEventListener('input', () => {
            if (input.value) {
                input.parentElement.classList.add('has-value');
            } else {
                input.parentElement.classList.remove('has-value');
            }
        });
    });

    // 处理表单提交
    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // 验证表单
        let isValid = true;
        
        if (!validatePhone(phoneInput.value)) {
            showError(phoneError, '请输入正确的手机号');
            isValid = false;
        }
        
        if (!validatePassword(passwordInput.value)) {
            showError(passwordError, '密码至少6位，包含字母和数字');
            isValid = false;
        }
        
        if (passwordInput.value !== confirmPasswordInput.value) {
            showError(confirmPasswordError, '两次输入的密码不一致');
            isValid = false;
            // 清空两个密码输入框
            passwordInput.value = '';
            confirmPasswordInput.value = '';
            // 移除输入框的 has-value 类
            passwordInput.parentElement.classList.remove('has-value');
            confirmPasswordInput.parentElement.classList.remove('has-value');
        }

        if (!isValid) return;

        // 显示加载状态
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';

        try {
            // 发送注册请求到user模块后端
            const response = await fetch('http://localhost:8080/api/users/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: phoneInput.value, // 使用手机号作为用户名
                    password: passwordInput.value,
                    nickname: phoneInput.value, // 使用手机号作为昵称
                    phone: phoneInput.value,
                    gender: 0, // 默认性别为未知
                    email: '',
                    gameUid: '',
                    avatar: ''
                })
            });

            const data = await response.json();

            if (response.ok) {
                // 保存用户信息
                localStorage.setItem('user', JSON.stringify(data.data));
                // 显示成功消息
                submitBtn.innerHTML = '<i class="fas fa-check"></i> 注册成功';
                submitBtn.classList.add('success');
                // 延迟跳转到登录页
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1000);
            } else {
                // 优先展示后端返回的 message
                submitBtn.innerHTML = '<i class="fas fa-times"></i> 注册失败';
                submitBtn.classList.add('error');
                if (data.message && data.message.includes('手机号')) {
                    showError(phoneError, data.message);
                } else if (data.message && data.message.includes('用户名')) {
                    showError(phoneError, data.message);
                } else {
                    showError(phoneError, data.message || '注册失败，请稍后重试');
                }
                setTimeout(() => {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '注册';
                    submitBtn.classList.remove('error');
                }, 3000);
            }
        } catch (error) {
            console.error('注册错误:', error);
            // 网络异常兜底
            submitBtn.innerHTML = '<i class="fas fa-times"></i> 注册失败';
            submitBtn.classList.add('error');
            showError(phoneError, '注册失败，请稍后重试');
            setTimeout(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '注册';
                submitBtn.classList.remove('error');
            }, 3000);
        }
    });
}); 